//
//  NewsDetailViewController.m
//  Fireball
//
//  Created by 俞渊华 on 2017/12/8.
//  Copyright © 2017年 俞渊华. All rights reserved.
//

#import "NewsDetailViewController.h"
#import "MoreReplyView.h"   ///更多回复
#import "NewsNavigation.h"

#import "NewsHeaderView.h"
#import "ZYShareView.h"

#import "AticleDetailModel.h"

///文章评论
#import "CommentSectionView.h"
#import "CommentCell.h"
#import "NewsCommentTool.h"
#import "ZInputToolbar.h"

#import "AticleComment.h"


@interface NewsDetailViewController ()
<
UITableViewDataSource,
UITableViewDelegate,
CommentToolDelegate,
ZInputToolbarDelegate
>

@property(nonatomic, strong)NewsNavigation *navView;
/// 新闻标题的高度
@property(nonatomic, assign)CGFloat titleHeight;

@property(nonatomic, strong)UITableView *tableView;

@property(nonatomic, strong)NewsHeaderView *headerView;
@property(nonatomic, strong)ZYShareView *shareView;
@property(nonatomic, strong)AticleDetailModel *detailModel;

@property(nonatomic, strong)NewsCommentTool *commentTool;
@property(nonatomic, strong)ZInputToolbar *inputToolbar;
@property(nonatomic, strong)MoreReplyView *moreReply;
@property(nonatomic, strong)NSArray *commentArray;

@property(nonatomic, strong)NSMutableDictionary *commentDict;
/// 要回复的评论
@property(nonatomic, strong)AticleComment *commentModel;
@property(nonatomic, assign)BOOL commentSub;

@end

@implementation NewsDetailViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"news_more"] style:UIBarButtonItemStylePlain target:self action:@selector(rightBarButtonItemClick)];
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor xm_middleColor];
    self.navigationItem.titleView = self.navView;
    self.titleHeight = [self.model.Title xm_sizeWithFont:[UIFont xm_medium:22.0] maxW:SCREEN_WIDTH - 40].height;
    
    [self setup];
    
    [self getAticleInfo];
    [self getAticleCommentInfo];
}

- (void)setup {
    
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.commentTool];

}
- (void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    self.tableView.frame   = CGRectMake(0, 0, self.view.width, self.view.height - kTabBarHeight);
    self.xm_backgroundColor = [UIColor colorWithWhite:1 alpha:1];
    self.commentTool.frame = CGRectMake(0, self.view.height - kTabBarHeight, self.view.width, kTabBarHeight);
}

#pragma mark -

- (void)rightBarButtonItemClick{
    
    
}
#pragma mark - CommentToolDelegate
-(void)commentToolSelectedIndex:(NSInteger)index{
    if (index == 0) {//评论
        
    }else if (index == 2) {//分享
        
    }
}
/// 评论文章
-(void)commentToolTextViewClick{
    self.commentSub = NO;
    [self.commentDict setObject:@(0) forKey:@"CommentID"];
    [self.inputToolbar.textInput becomeFirstResponder];
}
///回复
-(void)replyWithModel:(AticleComment *)model{
    self.commentModel = model;
    self.commentSub = NO;
    [self.commentDict setObject:@(model.CommentID) forKey:@"CommentID"];
    [self.inputToolbar.textInput becomeFirstResponder];
}
///回复
-(void)replySubCommentWithModel:(AticleComment *)model{
    self.commentModel = model;
    self.commentSub = YES;
    [self.commentDict setObject:@(model.CommentID) forKey:@"CommentID"];
    [self.inputToolbar.textInput becomeFirstResponder];
}

#pragma mark - ZInputToolbarDelegate
-(void)inputToolbar:(ZInputToolbar *)inputToolbar sendContent:(NSString *)sendContent {
    // 清空输入框文字
    if (self.commentSub) {
        [self.commentDict setObject:[NSString stringWithFormat:@"%@||%@",sendContent,self.commentModel.NikeName] forKey:@"Content"];
    }else{
        [self.commentDict setObject:sendContent forKey:@"Content"];
    }

    [FBNetworkTool get:@"articleapi/com.AddCommontInfo" parameters:self.commentDict showHUD:YES success:^(XMHttpResponseModel *responseModel) {
        if (responseModel.code == 200) {
            [inputToolbar sendSuccessEndEditing];

            ///请求成功重新请求评论列表
            [self getAticleCommentInfo];
        }
    } failure:^(NSError *error) {
        
    }];
}

#pragma mark -
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.commentArray.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 100;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    static NSString *viewIdentfier = @"commentHeaderView";
    CommentSectionView *sectionHeadView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:viewIdentfier];
    if(!sectionHeadView){
        sectionHeadView = [[CommentSectionView alloc] initWithReuseIdentifier:viewIdentfier];
    }
    WEAKSELF
    sectionHeadView.block = ^(AticleComment *model) {
        [weakSelf replyWithModel:model];
    };
    sectionHeadView.comment = self.commentArray[section];
    return sectionHeadView;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 15;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 3) {
        return 44;
    }
    return 25;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    AticleComment * comment = self.commentArray[section];
    if (comment.CommentChildrens.count > 3) {
        return 4;
    }
    return comment.CommentChildrens.count;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    static NSString *viewIdentfier = @"commentFooterView";
    UITableViewHeaderFooterView *footerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:viewIdentfier];
    if(!footerView){
        footerView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:viewIdentfier];
        footerView.contentView.backgroundColor = [UIColor whiteColor];
    }
    return footerView;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CommentCell * cell = [CommentCell cellWithTableView:tableView];
    AticleComment * comment = self.commentArray[indexPath.section];
    cell.commentCount = comment.CommentChildrens.count;
    cell.nickName = comment.NikeName;
    
    AticleComment * subComment = comment.CommentChildrens[indexPath.row];
    subComment.isMore = indexPath.row == 3;
    cell.comment = subComment;
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 3) {
        MoreReplyView * moreView = [[MoreReplyView alloc] init];
        moreView.comment = self.commentArray[indexPath.section];
        [kAppWindow addSubview:moreView];
        [UIView animateWithDuration:0.24 animations:^{
            moreView.y = 0;
        }];
    }else{
        AticleComment * comment = self.commentArray[indexPath.section];
        [self replySubCommentWithModel:comment.CommentChildrens[indexPath.row]];
    }
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CGFloat offsetY = scrollView.contentOffset.y;
    self.navView.hidden = offsetY <= (self.titleHeight + 60);
    [self.inputToolbar endEditing:YES];
}

#pragma mark - 网络请求
- (void)getAticleCommentInfo{
    NSDictionary * dict = @{@"CommentID":@"0",
                            @"ArticleID":@(self.model.ID),
                            @"PageInfo":@{@"CurrentPage":@(1),
                                          @"PageSize":@(10)
                                          },
                            };
    [FBNetworkTool get:@"articleapi/com.GetAticleCommentInfo" parameters:dict showHUD:YES success:^(XMHttpResponseModel *responseModel) {
        if (responseModel.code == 200) {
            self.commentArray = [AticleComment mj_objectArrayWithKeyValuesArray:responseModel.data];
            [self.tableView reloadData];
        }
    } failure:^(NSError *error) {
        
    }];
}
- (void)getAticleInfo{
    NSDictionary * dict = @{@"MenuType":@(self.model.ID),
                            @"ID":@(self.model.ID)
                            };
    [FBNetworkTool get:@"articleapi/com.GetAticleInfo" parameters:dict showHUD:YES success:^(XMHttpResponseModel *responseModel) {
        if (responseModel.code == 200) {
            self.detailModel = [AticleDetailModel mj_objectWithKeyValues:responseModel.data];
            
            self.headerView.detailModel = self.detailModel;
            self.navView.model = self.detailModel;
            self.commentTool.model = self.detailModel;
        }
    } failure:^(NSError *error) {
        
    }];
}












#pragma mark -

-(NewsNavigation *)navView{
    if (!_navView) {
        _navView = [[NewsNavigation alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH - 100, 44)];
        _navView.hidden = YES;
        
    }
    return _navView;
}


- (UITableView *)tableView{
    if (!_tableView) {
        UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        tableView.backgroundColor = [UIColor whiteColor];
        tableView.delegate = self;
        tableView.dataSource = self;
        tableView.tableFooterView = [UIView new];
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

        tableView.tableHeaderView = self.headerView;
        _tableView = tableView;
    }
    return _tableView;
}


-(NewsHeaderView *)headerView{
    if (!_headerView) {
        _headerView = [[NewsHeaderView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 100)];
        WEAKSELF
        _headerView.heightBlock = ^(CGFloat headerHeight) {
            weakSelf.headerView.height = headerHeight;
            
            [weakSelf.tableView beginUpdates];
            weakSelf.tableView.tableHeaderView = weakSelf.headerView;
            [weakSelf.tableView endUpdates];
        };
    }
    return _headerView;
}


- (NewsCommentTool *)commentTool{
    if (!_commentTool) {
        _commentTool = [[NewsCommentTool alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT - 49, SCREEN_WIDTH, 49)];
        _commentTool.delegate = self;
    }
    return _commentTool;
}
- (ZInputToolbar *)inputToolbar{
    if (!_inputToolbar) {
        _inputToolbar = [[ZInputToolbar alloc] initWithFrame:CGRectMake(0,self.view.height, self.view.width, 49)];
        _inputToolbar.textViewMaxLine = 5;
        _inputToolbar.delegate = self;
        _inputToolbar.placeholderLabel.text = @"优质评论将会被优先展示";
        [self.view addSubview:_inputToolbar];
    }
    return _inputToolbar;
}
-(MoreReplyView *)moreReply{
    if (!_moreReply) {
        _moreReply = [[MoreReplyView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT)];
        [kAppWindow addSubview:_moreReply];
    }
    return _moreReply;
}

-(NSMutableDictionary *)commentDict{
    if (!_commentDict) {
        _commentDict = [NSMutableDictionary dictionary];
        [_commentDict setObject:@(self.detailModel.ID) forKey:@"ArticleID"];
        [_commentDict setObject:@([UserAccountTool account].UserId) forKey:@"UserID"];
    }
    return _commentDict;
}




@end







